import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';

import 'package:zootix/services/zt_app_info.service.dart';
import 'package:zootix/util/zt_convert.dart';
import 'package:zootix/util/zt_logger_util.dart';

import '../constants/zt_constants.dart';

class TranslateComputeModel {
  String? content;
  String? languageCode;
  String? googleTranslationKey;
  TranslateComputeModel(
      {this.content, this.languageCode, this.googleTranslationKey});
  TranslateComputeModel.fromJson(Map<String, dynamic> json) {
    content = json['content'];
    languageCode = json['languageCode'];
    googleTranslationKey = json['googleTranslationKey'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = Map<String, dynamic>();
    data['content'] = content;
    data['languageCode'] = languageCode;
    data['googleTranslationKey'] = googleTranslationKey;
    return data;
  }
}

class ZtTranslateService extends GetxService {
  static ZtTranslateService get to => Get.find();
  final languageCode = RxString('');
  final autoTranslate = RxBool(true);
  Future<ZtTranslateService> init() async {
    ZtLoggerUtil()
        .info("[service-translate] Register google translate service");
    getDeviceLanguage();
    return this;
  }

  Future<void> getDeviceLanguage() async {
    Locale defaultLocale = WidgetsBinding.instance.window.locale;
    languageCode.value = defaultLocale.languageCode;
  }

  // Use a separate thread to translate
  Future<void> googleTranslate(String? content, Function? callback) async {
    final model = TranslateComputeModel(
        content: content,
        languageCode: languageCode.value,
        googleTranslationKey: await ZtAppInfoService.to
            .getConfigByCode('google_translation_key'));
    final value = await compute(requestGoogle, model);
    if (callback != null) {
      callback(value);
    }
  }
}

Future<String?> requestGoogle(TranslateComputeModel computeData) async {
  final dio = Dio(BaseOptions(
    connectTimeout: const Duration(seconds: 10),
  ));
  Map<String, String> data = {
    // "target": computeData.languageCode ?? 'en',
    "target": "zh-CN",
    "q": computeData.content ?? '',
    "format": 'text'
  };
  try {
    final response = await dio.post(ZtUrls.googleTranslate,
        queryParameters: {
          "key": computeData.googleTranslationKey,
        },
        data: data);
    if (response.data != null) {
      final translations = toList(response.data['data']['translations']);
      if (translations.isNotEmpty) {
        return translations[0]['translatedText'];
      }
    }
    return null;
  } catch (e) {
    return null;
  }
}
